package project1;

import java.net.DatagramSocket;
import java.net.InetAddress;

public class ServiceRegister {
	DatagramSocket requestSocket;
	DatagramSocket exchangeSocket;
	
	public ServiceRegister() {
	}
	
	public ServiceRegister(DatagramSocket requestSocket,
			DatagramSocket exchangeSocket) {
		this.exchangeSocket = exchangeSocket;
		this.requestSocket = requestSocket;
	}

	private IResponse sendData(String commandStr) {
		String ipPort = "";
		try {
			ipPort = Util.getOutAddressPort();
		} catch (Exception e) {
			System.out.println("[ERROR] Get outer ip address error. Please try again. ");
		}
			
		final byte newSeqNo = MainRequestThread.getNextSeqNo();
		ICommand commandObj = null;
		try {
			commandObj = ICommand.createInstanceFromCommand(commandStr, newSeqNo, InetAddress.getByName(ipPort.split(" ")[0]).getAddress());
		} catch (Exception e) {
			System.out.println("[ERROR] " + e.getMessage());
			MainRequestThread.decrementSeqNo();
		}
		
		MainRequestThread.registerNewThread(commandObj, newSeqNo);
		
		return WaitResponseThread.getResponce(commandObj.getSeqNum());
	}
	
	public IResponse sendRegister(String serviceName, String portNum, String data) {
		return sendData("r " + serviceName + " " + portNum + " " + data);
	}
	
	public IResponse sendUnRegister(String serviceName) {
		return sendData("u " + serviceName);
	}
	
	public IResponse sendFetch(String namePre) {
		return sendData("f " + namePre);
	}
	
	public IResponse sendFetch() {
		return sendData("f");
	}
	
	public IResponse sendProbe() {
		return sendData("p");
	}
	
	public void clear() {
		if (requestSocket != null && !requestSocket.isClosed()) requestSocket.close();
		if (exchangeSocket != null && !exchangeSocket.isClosed()) exchangeSocket.close();
	}
}
